package com.example.openim.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.openim.service.TYRZUserService;
import com.example.openim.utils.AesGcmUtil;
import com.example.openim.utils.HttpsUtil;
import com.example.openim.utils.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.UUID;

/**
 * @description: 实现逻辑
 * @author: xhq
 * @create: 2025-11-05 16:38
 */
@Service
@Slf4j
public class TYRZUserServiceImpl implements TYRZUserService {

    @Value("${TYRZ.URL}")
    public String URL;

    @Value("${TYRZ.APP_ID}")
    public String APP_ID;

    @Value("${TYRZ.SECRET}")
    public String SECRET;

    @Autowired
    private Md5Utils md5Utils;

    /**
     * 查询用户信息
     *
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject queryUserInfo(String accessToken) {
        JSONObject userInfo = null;
        UUID uuid = UUID.randomUUID();
        Long timestamp = System.currentTimeMillis();
        JSONObject dataJson = new JSONObject();
        dataJson.put("accessToken", accessToken);
        String data = AesGcmUtil.encrypt(dataJson.toJSONString(), md5Utils.lowMD5_32(SECRET));
        String sign = APP_ID + data + timestamp + uuid;
        String signMd5 = md5Utils.lowMD5_32(sign);

        //组装参数
        JSONObject bodyJson = new JSONObject();
        bodyJson.put("appId", APP_ID);
        bodyJson.put("uuid", uuid);
        bodyJson.put("timestamp", timestamp);
        bodyJson.put("data", data);
        bodyJson.put("sign", signMd5);
        String url = URL + "/oauth2/public/getUserInfo";
        try {
            String result = HttpsUtil.sendPostMap(url, null, null, bodyJson.toJSONString());
            log.info("统一认证返回信息："+ result);
            JSONObject res = JSONObject.parseObject(result);
            if (res.getInteger("code") == 200) {
                //将返回报文转换为json
                JSONObject resJson = JSONObject.parseObject(res.getString("result"));
                String resData = resJson.getString("data");
                Long resTime = resJson.getLong("timestamp");
                String resUuid = resJson.getString("uuid");
                String resSign = resJson.getString("sign");
                String resMd5 = md5Utils.lowMD5_32(resData + resTime + resUuid);
                if (resSign.equals(resMd5)) {
                    String Aes = AesGcmUtil.decrypt(resData, md5Utils.lowMD5_32(SECRET));
                    userInfo = JSONObject.parseObject(Aes);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("查询用户信息结果："+ userInfo);
        return userInfo;

    }
}
